/**
 * @author KujoMiva
 * @name user.js
 * @desc 用户相关vuex
 * @time 2020年05月15日 14:58:43 星期五
 */

import { resetRouter } from '@/router';
import { setToken, getToken, removeToken } from '@/utils/auth';
// api
import { logout, userInfo,
    // register,
    login as loginAPI,
    // resetPassword
} from '@/axios/userAccount';


export default {
    namespaced: true,
    state: {
        token: getToken(),
        nickname: '',
        avatar: '',
        roles: [],
        userInfo: {},
    },
    mutations: {
        SET_TOKEN: (state, token) => {
            state.token = token;
        },
        SET_NAME: (state, nickname) => {
            state.nickname = nickname;
        },
        SET_AVATAR: (state, avatar) => {
            state.avatar = avatar;
        },
        SET_ROLES: (state, roles) => {
            state.roles = roles;
        },
        SAVE_USER_INFO: (state, data) => {
            state.userInfo = data;
        },
    },
    actions: {
        async login({ commit }, loginParams) {
            const result = await loginAPI(loginParams);
            const { code, data: token } = result;
            if (code === 200) {
                setToken(token); // 把token保存到 cookie中
                commit('SET_TOKEN', token); // 把 token保存到vuex中
            }
            // 无论结果如何, 抛出结果可以让其他程序也参与处理
            return result;
        },
        // get userinfo
        async  getInfo({ commit }) {
            const result = await userInfo();
            const { nickname, avatar } = result.data;
            // 这里操作mutations
            commit('SAVE_USER_INFO', result.data);
            commit('SET_NAME', nickname);
            commit('SET_AVATAR', avatar);
            commit('SET_ROLES', []);
            // 抛出数据
            return result.data;
        },
        // logout
        async logout({ commit }) {
            await logout();
            commit('SET_TOKEN', '');
            commit('SET_ROLES', []);
            commit('SAVE_USER_INFO', {});
            removeToken();
            resetRouter();
        },
    },
};
